import { reactive } from "vue";
//校验函数

//校验用户名,value输入值
export const validateUsername = (rule, value, callback) => {
  //英文字母、数字、下划线或者短横线3-16位
  let reg = /^[a-zA-Z0-9-_]{3,16}$/;
  // console.log(value);
  if (reg.test(value)) {
    callback();
  } else {
    callback(new Error("用户名必须是英文字母、数字、下划线或者短横线3-16位"));
  }
};
//校验密码
export const validatePassword = (rule, value, callback) => {
  if (value.length < 3) {
    callback(new Error("密码长度不能小于3位"));
  } else {
    callback();
  }
};
//校验验证码
export const validateCapture = (rule, value, callback) => {
  if (value.length < 5) {
    callback(new Error("验证码不能小于5位"));
  } else {
    callback();
  }
};

//手机号校验
export const validatePhone = (rule, value, callback) => {
  let reg = /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
  if (reg.test(value)) {
    callback();
  } else {
    callback(new Error("手机号格式不正确"));
  }
};
//手机号验证码校验
export const validateCode = (rule, value, callback) => {
  if (value.length === 5) {
    callback();
  } else {
    callback(new Error("验证码必须5位"));
  }
};
//手机短信登录校验规则
export const smsRules = reactive({
  phone: [{ validator: validatePhone, trigger: "blur" }],
  code: [{ validator: validateCode, trigger: "blur" }],
});
//用户密码登录校验规则
export const commonRules = reactive({
  username: [{ validator: validateUsername, trigger: "blur" }],
  password: [{ validator: validatePassword, trigger: "blur" }],
  captcha: [{ validator: validateCapture, trigger: "blur" }],
});
//表单提交
/**
 *captcha
 * @param {Object} formEl 表单的引用对象
 * @param {Function} successCallback 表单校验通过的回调函数
 * @param {Function} faildCallback 表单校验失败的回调函数
 */
export const userSubmitForm = (successCallback, faildCallback) => (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (successCallback) {
        successCallback();
      }
    } else {
      if (faildCallback) {
        faildCallback();
      }

      return false;
    }
  });
};
